package pro_cons;

import senders.Sender;
import senders.SenderFactory;
import com.rabbitmq.client.*;
import utils.Mode;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author lishunlin110
 * @version 1.0
 * @description: 生产者类
 * @date 2021/12/10 19:32
 */
public class Producer {
    private final Mode mode;
    private Connection connection;
    private String exchangeName;
    private String queueName;
    private String routingKey;

    private Sender sender;

    public Producer(Mode mode, Connection connection, String exchangeName, String queueName, String routingKey) throws IOException {
        this.mode = mode;
        this.connection = connection;
        this.exchangeName = exchangeName;
        this.queueName = queueName;
        this.routingKey = routingKey;
        this.sender = SenderFactory.getSender(mode, connection, queueName, exchangeName, routingKey);
    }

    public void produce(String product) throws IOException, TimeoutException {
        sender.send(product);
    }

    public Mode getMode() {
        return mode;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) throws IOException, TimeoutException {
        this.connection = connection;
        this.sender.closeChannel();
        this.sender.closeConnection();
        this.sender = SenderFactory.getSender(this.mode, this.connection, this.queueName, this.exchangeName, this.routingKey);
    }

    public String getExchangeName() {
        return exchangeName;
    }

    public void setExchangeName(String exchangeName) throws IOException, TimeoutException {
        this.exchangeName = exchangeName;
        this.sender.closeChannel();
        this.sender.closeConnection();
        this.sender = SenderFactory.getSender(this.mode, this.connection, this.queueName, this.exchangeName, this.routingKey);
    }

    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) throws IOException, TimeoutException {
        this.queueName = queueName;
        this.sender.closeChannel();
        this.sender.closeConnection();
        this.sender = SenderFactory.getSender(this.mode, this.connection, this.queueName, this.exchangeName, this.routingKey);
    }

    public String getRoutingKey() {
        return routingKey;
    }

    public void setRoutingKey(String routingKey) throws IOException, TimeoutException {
        this.routingKey = routingKey;
        this.sender.closeChannel();
        this.sender.closeConnection();
        this.sender = SenderFactory.getSender(this.mode, this.connection, this.queueName, this.exchangeName, this.routingKey);
    }

    public Sender getSender() {
        return sender;
    }

    public void setSender(Sender sender) {
        this.sender = sender;
    }
}
